from helpers import Fetching
import datetime
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ Hourly cron job class """
    def get(self):
        updateAll()
                
def runUpdateYahoo(phase):
        """ Update stocks data with Yahoo changes """    
        
        q_1 = db.GqlQuery("SELECT * FROM StocksData WHERE yahooPhase!=:1 LIMIT 0,10", phase)
        # If finished updating for today
        if q_1.count()==0:
            return 1

        for p in q_1:
            try:
                currYahooValue=float(Fetching.downloadYahooData(p.stockname))
                if currYahooValue==-1:
                    p.yahooPercentChange=1.0
                else:    
                    if p.yahooValue==0.0:
                        p.yahooPercentChange=1.0
                    else:
                        p.yahooupdatedate=datetime.datetime.today()
                        divideValue=round(currYahooValue/p.yahooValue,7)
                        #if divideValue<1:
                            #p.yahooPercentChange=divideValue
                        #else:    
                            #wholeValue=int(divideValue)
                            #p.yahooPercentChange=((divideValue-wholeValue) *10 ) + wholeValue
                        p.yahooPercentChange=divideValue
                    p.yahooValue=currYahooValue
                    p.precentChange=round(p.yahooPercentChange*p.precentChange,7)

            except:
                # Error downloading data (do not change the percentage of the stock)
                p.yahooPercentChange=1.0
                
            p.yahooPhase=phase
            p.put()

        return 0
        
    
        
         
def runUpdateUsersYahoo(phase):
        """ Update users stocks values after Yahoo update """
        
        q_1 = db.GqlQuery("SELECT * FROM TrendUsers WHERE yahooPhase!=:1 LIMIT 0,2", phase)
        # If finished updating for today
        if q_1.count()==0:
            return 1

        for trenduser in q_1:
            accumamount=0.0
            # Update stocks amount of user
            q_2 = db.GqlQuery("SELECT * FROM Stocks WHERE stockref!=NULL AND buyer=:1", trenduser.tuser)
            for stock in q_2:
                # Downloading data from google succeeded and date is up-to-date
                stock.currValueNotRounded*=stock.stockref.yahooPercentChange
                stock.userPrecentChange=round(stock.currValueNotRounded/stock.buyValue,7)
                stock.yahooupdatedate=datetime.datetime.today()
                stock.currValue = round(stock.currValueNotRounded,2)
                accumamount+=stock.currValue
                
                    #stock.userupdatedate=stock.stockref.updatedate
                #Update stock data
                stock.put()
            # Update ETF amount of user    
            q_3 = db.GqlQuery("SELECT * FROM Stocks WHERE basketref!=NULL AND buyer=:1 ", trenduser.tuser)
            
            for stock in q_3:
                # Accumulate sum update
                accumamount+=stock.currValue
                
            # Update user amount from investments
            trenduser.totalamount=accumamount+trenduser.bankamount
            
            trenduser.yahooPhase=phase
            trenduser.put()
        return 0    
        

def updateAll():
        """ Begin cron job - check if cron job needs to run """
        # Select cron job last finished time
        q_0 = db.GqlQuery("SELECT * FROM CronJ Limit 0,1")
        # Run only if today cron job is not finished
        result=q_0.fetch(1)
        if result[0].rundate<datetime.date.today():
            return
        
        q_1 = db.GqlQuery("SELECT * FROM YahooCronJ Limit 0,1")

        result=q_1.fetch(1)
        if result[0].runhour.hour<datetime.datetime.today().hour:      
            if runUpdateYahoo(result[0].phase)==1:
                    if runUpdateUsersYahoo(result[0].phase)==1:
                        result[0].runhour = datetime.datetime.today()
                        result[0].phase+=1
                        #Update last cron job finished job for today
                        result[0].put()
                
application = webapp.WSGIApplication(
                                     [('/crondir/cronjobhourly', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()